package com.cy.redis;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.BitSet;

public class BitSetUtils {


	/**
	 * 将BitSet对象转化为ByteArray
	 *
	 * @param bitSet
	 * @return
	 */
	public static byte[] bitSet2ByteArray(BitSet bitSet) {
		byte[] bytes = new byte[bitSet.size() / 8];
		for (int i = 0; i < bitSet.size(); i++) {
			int index = i / 8;
			int offset = 7 - i % 8;
			bytes[index] |= (bitSet.get(i) ? 1 : 0) << offset;
		}
		return bytes;
	}


	public static BitSet byteArray2BitSet(byte[] bytes) {
		BitSet bitSet = new BitSet(bytes.length * 8);
		int index = 0;
		for (byte aByte : bytes) {
			for (int j = 7; j >= 0; j--) {
				bitSet.set(index++, (aByte & (1 << j)) >> j == 1);
			}
		}
		return bitSet;
	}
	public static String byteArray2BitSetString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (byte aByte : bytes) {
			for (int j = 7; j >= 0; j--) {
				sb.append((aByte & (1 << j)) >> j == 1?"1":"0");
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		JedisCluster cluster = new JedisCluster(new HostAndPort("10.199.186.255", 6379));
		String key = "cy";
		String cy = cluster.get(key);

		System.out.println(byteArray2BitSetString(cy.getBytes()));
	}

}